package com.winter.main.exception;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Desc: 异常处理
 * Author: dushuang
 * Date: Create in 2018/4/26
 */
public class BusExceptionHandler implements HandlerExceptionResolver {

    private Logger logger = LogManager.getLogger(this);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ModelAndView mv = new ModelAndView();
        FastJsonJsonView view = new FastJsonJsonView();
        Map<String, Object> attributes = new HashMap<>();
        if (ex instanceof UnauthenticatedException) {
            attributes.put("resultCode", "1000001");
            attributes.put("message", "token错误!");
            logger.error("UnauthenticatedException:token错误!");
        } else if (ex instanceof UnauthorizedException) {
            attributes.put("resultCode", "1000002");
            attributes.put("message", "用户无权限!");
            logger.error("UnauthorizedException:验证未通过,用户无权限!");
        } else if (ex instanceof UnknownAccountException){
            attributes.put("resultCode", "1000003");
            attributes.put("message", "用户不存在!");
            logger.error("UnknownAccountException:验证未通过,用户不存在!");
        } else if (ex instanceof IncorrectCredentialsException){
            attributes.put("resultCode", "1000004");
            attributes.put("message", "错误的凭证!");
            logger.error("IncorrectCredentialsException:验证未通过,错误的凭证!");
        } else if (ex instanceof LockedAccountException){
            attributes.put("resultCode", "1000005");
            attributes.put("message", "账户已锁定!");
            logger.error("LockedAccountException :验证未通过,账户已锁定!");
        } else if (ex instanceof ExcessiveAttemptsException){
            attributes.put("resultCode", "1000006");
            attributes.put("message", "错误次数过多!");
            logger.error("ExcessiveAttemptsException :验证未通过,错误次数过多!");
        } else {
            attributes.put("resultCode", "1100000");
            attributes.put("message", "出现异常,访问失败!");
            ex.printStackTrace();
            logger.error("OtherException:"+ex.getMessage()+"!");
        }
        view.setAttributesMap(attributes);
        mv.setView(view);
        return mv;
    }
}
